package com.clockey.server.httpserver.netty;

import io.netty.handler.codec.http.QueryStringDecoder;

import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import com.alibaba.fastjson.JSON;
import com.clockey.server.httpserver.util.ConvertUtil;

public class Request {

	private QueryStringDecoder queryStringDecoder;
	private String queryString;// 请求体,post方式时才set

	// private boolean requestPostFl;
	/**
	 * @param name
	 * @return
	 */
	public String getParameter(String name) {
		Map<String, List<String>> params = queryStringDecoder.parameters();
		for (Entry<String, List<String>> entry : params.entrySet()) {
			String key = entry.getKey();
			List<String> values = entry.getValue();
			for (String value : values) {
				if (key.equals(name)) {
					return value;
				}
			}
		}
		return null;
	}

	public <T> T getJSONObject(Class<T> clazz) {
		return JSON.parseObject(queryString, clazz);
	}

	/**
	 * 如果json格式或序列化问题，将返回null
	 * 
	 * @return
	 */
	public Map<String, Object> getParameterMap() {
		return ConvertUtil.json2Map(queryString);
	}

	// public Object getJSONObject(Class<?> clazz){
	// return JSON.parseObject(queryString, clazz);
	// }

	protected QueryStringDecoder getQueryStringDecoder() {
		return queryStringDecoder;
	}

	protected void setQueryStringDecoder(QueryStringDecoder queryStringDecoder) {
		this.queryStringDecoder = queryStringDecoder;
	}

	public String getQueryString() {
		return queryString;
	}

	public void setQueryString(String queryString) {
		this.queryString = queryString;
	}

}
